package dhm.com.dhmshop.view.mine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.SystemClock;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ldf.calendar.Utils;
import com.ldf.calendar.component.CalendarAttr;
import com.ldf.calendar.component.CalendarViewAdapter;
import com.ldf.calendar.interf.OnSelectDateListener;
import com.ldf.calendar.model.CalendarDate;
import com.ldf.calendar.view.Calendar;
import com.ldf.calendar.view.MonthPager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.dhmshop.R;
import dhm.com.dhmshop.adapter.mine.MyFootAdapter;
import dhm.com.dhmshop.base.BaseActiity;
import dhm.com.dhmshop.base.Presenter.PressenterImpl;
import dhm.com.dhmshop.base.netWork.Constant;
import dhm.com.dhmshop.base.netWork.LoginContract;
import dhm.com.dhmshop.entity.Bean;
import dhm.com.dhmshop.entity.FootBean;
import dhm.com.dhmshop.utils.CustomDayView;
import dhm.com.dhmshop.utils.SpUtils;
import dhm.com.dhmshop.utils.ThemeDayView;
import dhm.com.dhmshop.utils.TimeUtil;

public class MyfootActivity extends BaseActiity implements LoginContract.IView {
    CoordinatorLayout content;
    MonthPager monthPager;
    RecyclerView rvToDoList;
    @BindView(R.id.edit)
    CheckBox edit;
    @BindView(R.id.line)
    LinearLayout line;

    private ArrayList<Calendar> currentCalendars = new ArrayList<>();
    private CalendarViewAdapter calendarAdapter;
    private OnSelectDateListener onSelectDateListener;
    private int mCurrentPage = MonthPager.CURRENT_DAY_INDEX;
    private Context context;
    private CalendarDate currentDate;
    private boolean initiated = false;
    private PressenterImpl pressenter;
    private String uid;
    private MyFootAdapter myFootAdapter;
    private FootBean footBean;
    private String isfirst="0";

    @Override
    protected int getLayout() {
        return R.layout.activity_myfoot;
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        ButterKnife.bind(this);
        getWindow().setStatusBarColor(getResources().getColor(R.color.main));
        pressenter = new PressenterImpl();
        pressenter.attachView(this);
        context = this;
        content = findViewById(R.id.content);
        monthPager = findViewById(R.id.calendar_view);
        //此处强行setViewHeight，毕竟你知道你的日历牌的高度
        monthPager.setViewHeight(Utils.dpi2px(context, 270));
        rvToDoList = findViewById(R.id.list);
        uid = SpUtils.getString(this, "uid");
    }

    @Override
    protected void initData() {
        //这里用线性显示 类似于listview
        rvToDoList.setLayoutManager(new GridLayoutManager(this, 2));
        myFootAdapter = new MyFootAdapter(this);
        myFootAdapter.setdeleteClick(new MyFootAdapter.OnClick() {
            @Override
            public void item(int posttion) {
                Map<String, String> map = new HashMap<>();
                map.put("token", Constant.TOKEN);
                map.put("uid", uid);
                map.put("fid", footBean.getData().get(posttion).getFid() + "");
                pressenter.sendMessage(MyfootActivity.this, Constant.DelFootList, map, Bean.class);

            }
        });
        rvToDoList.setAdapter(myFootAdapter);
        initCurrentDate();
        initCalendarView();
        getlist(TimeUtil.getCurrentDate());


    }

    private void getlist(String data) {
        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("uid", uid);
        map.put("foot_date", data);
        pressenter.sendMessage(this, Constant.FootList, map, FootBean.class);
    }

    /**
     * onWindowFocusChanged回调时，将当前月的种子日期修改为今天
     *
     * @return void
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && !initiated) {
            refreshMonthPager();
            initiated = true;
        }
    }

    /**
     * 初始化currentDate
     *
     * @return void
     */
    private void initCurrentDate() {
        currentDate = new CalendarDate();
    }

    /**
     * 初始化CustomDayView，并作为CalendarViewAdapter的参数传入
     */
    private void initCalendarView() {
        initListener();
        CustomDayView customDayView = new CustomDayView(context, R.layout.custom_day);
        calendarAdapter = new CalendarViewAdapter(
                context,
                onSelectDateListener,
                CalendarAttr.WeekArrayType.Monday,
                customDayView);
        calendarAdapter.setOnCalendarTypeChangedListener(new CalendarViewAdapter.OnCalendarTypeChanged() {
            @Override
            public void onCalendarTypeChanged(CalendarAttr.CalendarType type) {
                rvToDoList.scrollToPosition(0);
            }
        });
        initMarkData();
        initMonthPager();
    }

    @Override
    public void requesta(Object data) {

        if (data instanceof FootBean) {
            footBean = (FootBean) data;
            if (footBean.getCode() == 1) {
                myFootAdapter.setShopList(footBean.getData());
            } else {
                myFootAdapter.setShopList(new FootBean().getData());
                Toast.makeText(context, footBean.getMessage(), Toast.LENGTH_SHORT).show();
            }

            if (isfirst.equals("0")){
                isfirst = "1";
                new Thread() {
                    @Override
                    public void run() {
                        final long downTime = SystemClock.currentThreadTimeMillis();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                MotionEvent down = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_DOWN, 200, 500, 0);
                                rvToDoList.dispatchTouchEvent(down);
                            }
                        });

                        SystemClock.sleep(10);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                MotionEvent move = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_MOVE, 200, 30, 0);
                                rvToDoList.dispatchTouchEvent(move);
                            }
                        });

                        SystemClock.sleep(10);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                MotionEvent up = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_UP, 200, 10, 0);
                                rvToDoList.dispatchTouchEvent(up);
                            }
                        });
                    }
                }.start();

            }


        } else if (data instanceof Bean) {
            Bean bean = (Bean) data;
            Toast.makeText(context, bean.getMessage(), Toast.LENGTH_SHORT).show();
            Map<String, String> map = new HashMap<>();
            map.put("token", Constant.TOKEN);
            map.put("uid", uid);
            pressenter.sendMessage(this, Constant.FootList, map, FootBean.class);
        }

    }

    @Override
    public void fail(String error) {

    }

    /**
     * 初始化标记数据，HashMap的形式，可自定义
     * 如果存在异步的话，在使用setMarkData之后调用 calendarAdapter.notifyDataChanged();
     */
    private void initMarkData() {
        HashMap<String, String> markData = new HashMap<>();
        markData.put("2017-8-9", "1");
        markData.put("2017-7-9", "0");
        markData.put("2017-6-9", "1");
        markData.put("2017-6-10", "0");
        calendarAdapter.setMarkData(markData);
    }

    private void initListener() {
        onSelectDateListener = new OnSelectDateListener() {
            @Override
            public void onSelectDate(CalendarDate date) {
                refreshClickDate(date);
            }

            @Override
            public void onSelectOtherMonth(int offset) {
                //偏移量 -1表示刷新成上一个月数据 ， 1表示刷新成下一个月数据
                monthPager.selectOtherMonth(offset);
            }
        };
    }


    private void refreshClickDate(CalendarDate date) {
        currentDate = date;
        getlist(date.toString());
    }

    /**
     * 初始化monthPager，MonthPager继承自ViewPager
     *
     * @return void
     */
    private void initMonthPager() {
        monthPager.setAdapter(calendarAdapter);
        monthPager.setCurrentItem(MonthPager.CURRENT_DAY_INDEX);
        monthPager.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                position = (float) Math.sqrt(1 - Math.abs(position));
                page.setAlpha(position);
            }
        });
        monthPager.addOnPageChangeListener(new MonthPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPage = position;
                currentCalendars = calendarAdapter.getPagers();
                if (currentCalendars.get(position % currentCalendars.size()) != null) {
                    CalendarDate date = currentCalendars.get(position % currentCalendars.size()).getSeedDate();
                    currentDate = date;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    public void onClickBackToDayBtn() {
        refreshMonthPager();
    }

    private void refreshMonthPager() {
        CalendarDate today = new CalendarDate();
        calendarAdapter.notifyDataChanged(today);
    }

    private void refreshSelectBackground() {
        ThemeDayView themeDayView = new ThemeDayView(context, R.layout.custom_day_focus);
        calendarAdapter.setCustomDayRenderer(themeDayView);
        calendarAdapter.notifyDataSetChanged();
        calendarAdapter.notifyDataChanged(new CalendarDate());
    }

    @OnClick({R.id.back, R.id.edit, R.id.clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.edit:

                if (edit.isChecked()) {
                    edit.setText("完成");
                    edit.setTextColor(getResources().getColor(R.color.main));
                } else {
                    edit.setText("编辑");
                    edit.setTextColor(getResources().getColor(R.color.mainblack));
                }

                myFootAdapter.setIsdel(edit.isChecked());
                break;
            case R.id.clear:
                Map<String, String> map = new HashMap<>();
                map.put("token", Constant.TOKEN);
                map.put("uid", uid);
                pressenter.sendMessage(this, Constant.DelAllFootList, map, Bean.class);

                break;
            default:
        }
    }
}
